<template>
    <div style="display: flex;justify-content: space-between;">
        <a-form size="small" :model="pageData" layout="inline" style="margin-bottom: 10px;" ref="formRef">
            <a-form-item label="公司">
                <a-select class="bacClass" v-model="pageData.companyId" allow-search allow-clear
                    @focus="getTreeCompany()" :filter-option="false"
                    style="width:200px">
                    <a-option v-for="(item, index) in pageData.companyList" :value="item.value" :key="index">
                        {{ item.label }}
                    </a-option>
                </a-select>
            </a-form-item>
            <a-form-item label="月份">
                <a-month-picker class="bacClass" v-model="pageData.planMonthBegin" style="width:200px" />至
                <a-month-picker class="bacClass" v-model="pageData.planMonthEnd" style="width:200px" />
            </a-form-item>
            <a-form-item label="检查单号" field="planCode" :rules="[{ required: true, message: '检查单号必填' }]"
                :validate-trigger="['change', 'blur']">
                <a-select popup-container="html" class="bacClass" v-model="pageData.planCode" allow-search allow-clear
                    @focus="getPlancode('')" @search="getPlancode" @change="getEmployee()" :filter-option="false"
                    style="width:200px">
                    <a-option v-for="(item, index) in pageData.codeList" :value="item.planCode" :key="index">
                        {{ item.planCode }}
                    </a-option>
                </a-select>
            </a-form-item>
            <a-form-item v-if="tabKey == 1" label="审核员" field="employeeCode">
                <a-select popup-container="html" class="bacClass" v-model="pageData.employeeCode" allow-clear
                    @focus="getEmployee()" :filter-option="false" style="width:200px">
                    <a-option v-for="(item, index) in pageData.operatorList" :value="item.employeeCode"
                        :label="item.employeeName" :key="index">
                        {{ item.employeeCode + '/' + item.employeeName }}
                    </a-option>
                </a-select>
            </a-form-item>
        </a-form>
        <Toolbar :items="['查询', '导出']" @select="selectHandle" @export="exportExcel">
        </Toolbar>
    </div>
    <div class="cssTable">
        <a-tabs :lazy-load="true" :justify="true" :default-active-key="tabKey" @change="tabChange">
            <a-tab-pane title="个人检查" :key="1">
                <a-spin :loading="pageData.pageLoading" tip="加载中" dot
                    style="height:100%;width: 98.5%;z-index:999 ;margin-left: 13px;">
                    <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                        :style="{ height: pageData.rHeight - 200 + 'px' }" :suppressDragLeaveHidesColumns="true"
                        rowSelection="multiple" @grid-ready="gridReady" :defaultColDef="defaultColDef"
                        class='ag-theme-alpine' :rowData="pageData.tableList" :columnDefs="tableColumns"
                        :localeText="localeText1" @FilterChanged="FilterChangeds"></AgGridVuesCopys>
                </a-spin>
            </a-tab-pane>
            <a-tab-pane title="汇总检查" :key="2">
                <a-spin :loading="pageData.pageLoading" tip="加载中" dot
                    style="height:100%;width: 98.5%;z-index:999 ;margin-left: 13px;">
                    <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                        :style="{ height: pageData.rHeight - 200 + 'px' }" :suppressDragLeaveHidesColumns="true"
                        rowSelection="multiple" @grid-ready="gridReady2" :defaultColDef="defaultColDef"
                        class='ag-theme-alpine' :rowData="pageData.tableList" :columnDefs="tableColumns2"
                        :localeText="localeText1"  @FilterChanged="FilterChangeds"></AgGridVuesCopys>
                </a-spin>
            </a-tab-pane>
        </a-tabs>
    </div>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted, Ref } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { slicing } from '@/utils/caseFrimAndSecRig'
import { FormInstance } from "@arco-design/web-vue/es/form";
import { exportStyleExcel } from '@/api/Export2StyleExcel'

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
    pageLoading: false,
    rHeight: 0,
    tableList: [],
    companyId: null,
    companyName: '',
    companyList: [],
    planCode: '',
    codeList: [],
    employeeCode: '',
    operatorList: [],
    inspectContent: '',
    planMonthBegin:'',
    planMonthEnd:'',
})

const defaultColDef: any = {
    sortable: true,
    resizable: true,
    filter: true,
}
//个人
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}

const tableColumns: any = [
    { headerName: "检查单号", field: "planCode", width: 150, },
    { headerName: "检查名称", field: "planName", width: 150, },
    { headerName: "检查内容", field: "itemContent", width: 150, },
    { headerName: "要求次数", field: "inspectNumber", width: 150, },
    { headerName: "已查次数", field: "checkedNumber", width: 150, },
    { headerName: "公司", field: "companyName", width: 150, },
    { headerName: "审核员", field: "employeeName", width: 150, },
    { headerName: "个人次数", field: "personalNumber", width: 150, },
    { headerName: "合格次数", field: "qualifiedNumber", width: 150, },
    { headerName: "不合格次数", field: "unqualifiedNumber", width: 150, },
    { headerName: "机台", field: "machineCode", width: 150, },
    { headerName: "被审员工", field: "auditedEmployee", width: 150, },
    { headerName: "岗位", field: "operatorPosition", width: 150, },
]

//汇总
const gridOption2 = ref()
const colState2 = ref()
const gridReady2 = (params: any) => {
    gridOption2.value = params.api
    colState2.value = params.columnApi
}
const tableColumns2: any = [
    { headerName: "检查单号", field: "planCode", width: 150, },
    { headerName: "检查名称", field: "planName", width: 150, },
    { headerName: "检查内容", field: "inspectContent", width: 150, },
    { headerName: "要求次数", field: "inspectNumber", width: 150, },
    { headerName: "已查次数", field: "checkedNumber", width: 150, },
    { headerName: "审核员", field: "planOperator", width: 150, },
    { headerName: "合格次数", field: "qualifiedCount", width: 150, },
    { headerName: "不合格次数", field: "unqualifiedCount", width: 150, },
    {
        headerName: "合格率",
        field: "qualified",
        width: 150,
        cellRenderer: {
            template: `<span>{{ val.qualified + '%' }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                props.params.data.qualified = ((parseFloat(props.params.data.qualifiedCount) / parseFloat(props.params.data.checkedNumber)) * 100).toFixed(1)
                return {
                    val,
                }
            },
        },
    },
    {
        headerName: "目标合格率",
        field: "qualifiedRate",
        width: 150,
        cellRenderer: {
            template: `<span v-if="val.planCode != '合计'">{{ val.qualifiedRate + '%' }}</span>
            <span v-if="val.planCode == '合计'"></span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
    },
    {
        headerName: "是否合格",
        field: "isQualified",
        width: 150,
        cellRenderer: {
            template: `<span v-if="val.planCode != '合计'">{{ val.isQualified }}</span>
            <span v-if="val.planCode == '合计'"></span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
    },
    { headerName: "被审员工", field: "auditedEmployee", width: 150, },
    { headerName: "岗位", field: "operatorPosition", width: 150, },
    { headerName: "机台", field: "machineCode", width: 150, },
]

//查询
const formRef = ref<FormInstance>();
function doRefresh() {
    formRef.value?.validate().then((err: any) => {
        if (!err) {
            pageData.pageLoading = true
            let urlData = ''
            if (tabKey.value == 1) {
                urlData = "/qms/inspectionPlanResult/buildPersonalInspectionResultReport"
            } else if (tabKey.value == 2) {
                urlData = "/qms/inspectionPlanResult/buildInspectionDetailReport"
            }
            post({
                url: urlData,
                data: {
                    companyIds: pageData.companyId,
                    planCode: pageData.planCode,
                    planOperator: pageData.planOperator,
                    employeeCode: pageData.employeeCode,
                }
            })
                .then((res: any) => {
                    if (res.code === 200) {
                        if (tabKey.value == 1) {
                            res.data.forEach((o: any) => {
                                o.unqualifiedNumber = o.personalNumber - o.qualifiedNumber
                            })
                        } else {
                            res.data.forEach((o: any) => {
                                o.checkedNumber = o.qualifiedCount + o.unqualifiedCount
                                o.qualified = ((parseFloat(o.qualifiedCount) / parseFloat(o.checkedNumber)) * 100).toFixed(1)
                                if (o.qualified < o.qualifiedRate) {
                                    o.isQualified = '不合格'
                                } else {
                                    o.isQualified = '合格'
                                }
                            })
                        }

                        pageData.tableList = res.data
                        gridOption.value.setRowData(res.data)
                        counts(pageData.tableList)
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }
    })
}

const selectHandle = () => {
    doRefresh()
}

let tabKey = ref(1)
const tabChange = (e: any) => {
    tabKey.value = e
    doRefresh()
}

//员工
const getOperator = (val?: any) => {
    post({
        url: '/qms/inspectionEmployee/listInspectionEmployees',
        data: { employeeCode: val ? val : '' },
    }).then((res) => {
        if (res.code == 200) {
            pageData.operatorList = res.data
        } else {
            Message.error({
                content: res.message,
                duration: 5000,
            })
        }
    })
}

//检查单号下拉
const getPlancode = (val: any) => {
    post({
        url: '/qms/inspectionPlan/listInspectionPlans',
        data: {
            planCode: val ? val : '',
            planMonthBegin:pageData.planMonthBegin,
            planMonthEnd:pageData.planMonthEnd
        },
    }).then((res) => {
        if (res.code == 200) {
            pageData.codeList = res.data
        } else {
            Message.error({
                content: res.message,
                duration: 5000,
            })
        }
    })
}

//审核员下拉
const getEmployee = () => {
    if (pageData.planCode) {
        let data = pageData.codeList.filter((o: any) => o.planCode == pageData.planCode)
        let nameData = data[0].planOperator.split(',');
        let codeData = data[0].operatorCodes.split(',');
        pageData.operatorList = nameData.map((o: any, index: number) => {
            return {
                employeeName: o,
                employeeCode: codeData[index],
            };
        });
    } else {
        pageData.operatorList = []
        pageData.employeeCode = ''
    }
}

// 底部合计
function counts(data:any) {
    var sum1 = 0;
    var sum2 = 0;
    var sum3 = 0;
    var sum4 = 0;
    var sum5 = 0;
    var sum6 = 0;
    if (tabKey.value == 1) {
        for (var i = 0; i < data.length; i++) {
            sum1 = sum1 + data[i].inspectNumber;
            sum2 = sum2 + data[i].checkedNumber;
            sum3 = sum3 + data[i].personalNumber;
            sum4 = sum4 + data[i].qualifiedNumber;
            sum5 = sum5 + data[i].unqualifiedNumber;
            sum6 = (sum6 + data[i].qualified) / data.length
        }
        var nowRows = [
            { planCode: '合计', inspectNumber: sum1, checkedNumber: sum2, personalNumber: sum3, qualifiedNumber: sum4, unqualifiedNumber: sum5, qualified: sum6 + '%' }
        ];
        gridOption.value.setPinnedBottomRowData(nowRows);
    } else {
        for (var i = 0; i < data.length; i++) {
            sum1 = sum1 + data[i].inspectNumber;
            sum2 = sum2 + data[i].checkedNumber;
            sum3 = sum3 + data[i].qualifiedCount;
            sum4 = sum4 + data[i].unqualifiedCount;
            sum5 = (sum5 + data[i].qualified) / data.length
        }
        var nowRows2 = [
            { planCode: '合计', inspectNumber: sum1, checkedNumber: sum2, qualifiedCount: sum3, unqualifiedCount: sum4, qualified: sum5 + '%', }
        ];
        gridOption2.value.setPinnedBottomRowData(nowRows2);
    }
}

// 导出
const exportExcel = () => {
    if (tabKey.value == 1) {
        let header = tableColumns.map((o: any) => { return o.headerName; });
        let filterCols = tableColumns.map((c: any) => { return c.field; });
        let data = formatJson(filterCols, pageData.tableList);
        exportStyleExcel({ header, data, filename: '个人检查报表.xlsx' })
    } else {
        let header = tableColumns2.map((o: any) => { return o.headerName; });
        let filterCols = tableColumns2.map((c: any) => { return c.field; });
        let data = formatJson(filterCols, pageData.tableList);
        exportStyleExcel({ header, data, filename: '汇总检查报表.xlsx' })
    }
}

const formatJson = (filterVal: any, jsonData: any) => {
    return jsonData.map((v: any) => filterVal.map((j: any) => {
        if (j == 'unqualifiedNumber' || j == 'checkedNumber' || j == 'qualified') {
            if (!v[j]) {
                return 0;
            }
        }
        if (j == 'qualified' || j == 'qualifiedRate') {
            return v[j] + '%'
        }
        else {
            if (!v[j])
                return '';
            else
                return v[j];
        }
    }))
}

const getTreeCompany = () => {
  post({
    url: 'org/baCompany/getTreeCompanyOrDepartment',
    data: {},
  }).then(({ data, code }: any) => {
    if (code === 200) {
      pageData.companyList = data[0].children.filter((o: any) => o.label == '织造中心')[0].children
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}

const FilterChangeds = (params:any)=>{
    let data: any = {
    list: [],
  }
  params.api.forEachNodeAfterFilter((row: any) => {
    data.list.push(row.data)
  })
counts(data.list)
}


onMounted(() => {
    pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
    //弹出层的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight;
    }
    getTreeCompany()
})
</script>

<style lang='less' scoped>
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

:deep(.arco-select-view-multiple.arco-select-view-disabled .arco-select-view-tag) {
    color: #4e5969 !important;
    ;
    background-color: white;
    border-color: white;
    font-size: 14px
}
</style>